package com.sky.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {

        log.info("微信用户登录：{}", userLoginDTO);

            String openid = getOpenid(userLoginDTO.getCode());
            //判断openid是不是空的，抛出异常
            if (openid == null){
                throw new RuntimeException("登录失败");
            }

            //判断这个openid在数据库存不存在，如果不存在说明是新用户
            User user = userMapper.getByOpenid(openid);
            if(user == null){
                user = User.builder()
                        .openid(openid)
                        .createTime(LocalDateTime.now())
                        .build();
                //新用户自动注册
                userMapper.insert(user);
            }

            //返回用户信息
            return user;
    }


    /**
     * 调用微信接口获得用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code) {
        //调用接口获得诶新用户的openid
        log.info("微信用户登录，code：{}", code);

        String openid = null;

        OkHttpClient client = new OkHttpClient();
        HttpUrl url = HttpUrl.parse(UserServiceImpl.WX_LOGIN_URL)
                .newBuilder()
                .addQueryParameter("appid", weChatProperties.getAppid())
                .addQueryParameter("secret", weChatProperties.getSecret())
                .addQueryParameter("js_code", code)
                .addQueryParameter("grant_type", "authorization_code")
                .build();

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        try (Response response = client.newCall(request).execute()) {

            String responseBody = response.body().string();


            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode node = objectMapper.readTree(responseBody);
            openid = node.path("openid").asText();


        } catch (IOException e) {
            e.printStackTrace();
        }
        return openid;
    }

}
